# -*- coding: utf-8 -*-
'''
@文件    :middlewares.py
@说明    :中间件
@时间    :2025/08/08 03:21:00
@作者    :浪晋
@版本    :1.0
'''
import traceback
import uuid
import time
from fastapi.requests import Request
from fastapi.responses import Response
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from app.core.database import record_request_log
from app.core.response import ERROR
from app.core.plugin import ctx
from app.core.logger import logger


class HttpLogMiddleware(BaseHTTPMiddleware):
    async def before_request(self, request: Request):
        """请求前操作"""
        request_id = uuid.uuid4()
        ctx.set("stack", request_id)
        request.scope['request_id'] = f'{request_id}'
        request.scope['start_time'] = time.perf_counter()


    async def after_request(self, response: Response):
        """请求后操作"""
        return response

    async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
        try:
            logger.info(f"{50*'='+ '>'}请求开始{'<'+'='*50}")
            await self.before_request(request)
            response = await call_next(request)
        except Exception as exc:
            response = ERROR(msg=str(exc))
            errorlog = traceback.format_exc()
            response = await record_request_log(request, response, errorlog)
        finally:
            response = await self.after_request(response)
            logger.info(f"{50*'='+ '>'}请求完成{'<'+'='*50}")
            return response
        
